#!/usr/bin/python
# -*- coding: utf -*- 
from xmpp import *
from sys import argv
from time import sleep
from random import *
from sys import maxint
from time import *
import os, xmpp, time, sys, time

japytName = 'Japyt'
japytVersion = 'v0.5-rSVN-beta'
capsNode = 'http://japyt.googlecode.com'
capsVersion = japytVersion[:4]
#japytName = 'Psi+'
#japytVersion = '0.13.302 Beta (Mar 15 2009)'
#capsNode = 'http://psi-im.org/caps'
#capsVersion = '0.13-dev-rev2'

def os_version():
	jSys = sys.platform
	jOs = os.name
	japytPyVer = sys.version
	japytPyVer = japytPyVer.split(',')
	japytPyVer = japytPyVer[0]+')'

	if jOs == u'posix':
	        osInfo = os.uname()
		if osInfo[4].count('iPhone'):
			if osInfo[4].count('iPhone1,1'):
				japytOs = 'iPhone 2G'
			elif osInfo[4].count('iPhone1,2'):
				japytOs = 'iPhone 3G'
			else:
				japytOs = 'iPhone Unknown (platform: '+osInfo[4]+')'

			if osInfo[3].count('1228.7.37'):
				japytOs += ' FW.2.2.1'
			elif osInfo[3].count('1228.7.36'):
				japytOs += ' FW.2.2'
			else:
				japytOs += ' FW.Unknown ('+osInfo[3]+')'


			japytOs += ' ('+osInfo[1]+') / Python v'+japytPyVer
		else:
		        japytOs = osInfo[0]+' ('+osInfo[2]+'-'+osInfo[4]+') / Python v'+japytPyVer

	elif jSys == 'win32':
	        def get_registry_value(key, subkey, value):
	            import _winreg
	            key = getattr(_winreg, key)
	            handle = _winreg.OpenKey(key, subkey)
	            (value, type) = _winreg.QueryValueEx(handle, value)
	            return value
	        def get(key):
	            return get_registry_value(
	                "HKEY_LOCAL_MACHINE", 
	                "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
	                key)
	        osInfo = get("ProductName")
	        spInfo = get("CSDVersion")
	        buildInfo = get("CurrentBuildNumber")
	        japytOs = osInfo+' '+spInfo+' (Build: '+buildInfo+') / Python v'+japytPyVer
	else:
	        japytOs = 'unknown'
	return japytOs

japytOs = os_version()


print u'\n---------------------------------------'
print u'Client:', japytName
print u'Version:', japytVersion
print u'OS:', japytOs
print u'---------------------------------------\n'

photodata = 'iVBORw0KGgoAAAANSUhEUgAAADsAAAA8CAYAAADYIMILAAAABGdBTUEAAFjH/EfgAgAAACBjSFJNAAB6JQAAgIMAAPn/AACA5gAAdS4AAOpfAAA6lwAAF29p5MQrAAAVeElEQVR4nGJgwA2YbWxtAp88fbL0+/fvZ/79+/fn/yAEIHeB3AdyJ8i9IHfj8hBAAGFFPDw86ufPnz91//79gfYLSQDkXpC7Qe7H5i+AAMJA2TnZxffu3fs20A6nBIDcD/IHut8AAggF9fb19lASm99fv/7/4OTJ/wsMDP4fVFP7f1pD4/9VIL4GxBeA+BAQr1JW/n9+8eL/3x88+P/9zRvq+RANgPwB8g+y/wACCI4cHB1iyPXoi5s3/59tafl/ysbm/w15+f83GBj+XwTi80B8BorPQcWuAfFtYeH/l7S0/p+wt/9/sbf3/8sbN6jrUygA+QfkL5gfAQIIhrhu3LjxHJjZ/5OCnwIdeaOu7v9pXd3/t4GeuAz11CWop0CePQsVg2GQx68CMShAbgHxTZCYvv7/6/X1/18AHUeqGwjha9evPQD5D+RJgAACIxdXlzRgOifZoNPFxf/vQj13GuqJS/z8//erqv9f5ub/f3Fs/v+JYTn/64Ly/pf45fzPdk/7X+yS9L/IMvj/NCm1/5sExf9fY2IGexqkd5+R2f8Lm7f9//PzJ9U8C/IXyH8gfwIEEAixrFy1chs5Bl1ISAB7FBxbjIz/N/iG/q8omPDfsXDpf4va7UC87b9Fzdb/5jVb/ptXb/5vXrUJiDf+N6/c8N+8ZPl/15SJ/8O9c//PltX6fxXo6etAc3aLyvxfWVD3/8vnr1Tz8PLly7eC/AkQQCDPCly4cOEJJZ69p6T0f2Zi4X8boEcs6nZg92g1kkcr1/83r1gHxGv/m5ev+W+VN/9/oFfW/0Vy2uBYPsgn8r83s/b/1x+/qOLZy5cvvwD5EyCAQJ6Vu3Xr1re/f//+JxVfiIz8fx/ouKOxSf8t63eCPWoFxAULT/2ftP3a/+gpBzFj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AIKIIDAayomTZ7078GDB//JxZ8ezkeZisA+KIbdo6A8+uHhFrA5Gd0f4Y4tq18Irkdf39tHlBuQPaqd8BNFbsKECaClQfoAAQReLZOdk3n14cOH/8nFzx5dBcZqCHRQDFeMYmvnWoELo98XY/+/fHgGbFZcI6IkdUm/9P/omUd47T569un/qKbPCI8m/vx/+fpjFDUg/wH9qQsQQOB1UBraGmtWrVpFtmcfPnzw/939VcAGvi+JHgUWRKcgraJ/pxz//z7h/v/fcav/ZXULUPqpIA9UzXj/f+n2l3AM4nuXf0VRZ5v7HcOjIH+B/AdaBwUQQOAVbkCcB+zNf6YkdkH47cNt///ciEcMcyKN5+Jt/iG1c0GN+t9n4/6v2Xblv2z4b5wDasiY3/cv2PPY3AT01xeQ/0D+BAggBuiaPn8VNZV9oAmgR48eUYSfPrr+/+O9hUBPZwA96wodQkHz6ClEjMJ7Licd/v84n/H/4+3lQDPuwM2bvvYNOJmCYhfZg6CAAMVsx+K3/6/ceILVLSD/gPwF8h/InwABxABdrakHxHVBIUF3161b9//x48cU46eP7/5/8ej8/0/3V/z/erMVWIDlA2M8ChjLwKbkeWBT8nI8sG9b/P/T1c7/nx5s/v/swUWgvgdUsRuEQf4A+QfkL6j/WAACiAEKhKG+n+Hs6nwbmM7/UsvSgcAg94P8AfIPEAdA/ccAEEAwBIpdJSBOAOI5rKysh7u6uj5u3LgRPI05VDDIvSB3s7OzHwH5A+ofJVisAgQQMmIHYlUgjgbifiDeoKyifDkvP+9lb1/vp82bN/8frBjkvuKS4lcg94LcDXV/NNQ/7MCeHdiDAAGEjtiAWBqInYG4FIhnATGo2N4GxHuBeP8gxHuh7lsLdS/I3S5Qf7DBPAqiAQIIm4dBsrxArAnEvkCcxQDJ5N3QEBsUGOh4GLsb6r5sqHs1oe5nQvEU0LMAAYTNszAASuegakkWiEE7oEAlmsEgxCB3qQM9IwvEAgxI+RPkQeSYBQgwADFRmFQH7VnlAAAAAElFTkSuQmCC'

#-----------------------------------------------------------------------------
def vcard(vcl, jidname):
        global photodata
        i = Node('iq', {'id': 0, 'type': 'set'}, payload = [Node('vCard', {'xmlns': NS_VCARD}, [Node('FN', {}, 'JaPyT (Jabber Python Transport for iPhone)'),
                                                                                                Node('NICKNAME', {}, jidname),
                                                                                                Node('BDAY', {}, '2009-02-21'),
                                                                                                Node('URL', {}, 'http://japyt.googlecode.com'),
                                                                                                Node('PHOTO', {}, [Node('TYPE', {}, 'image/png'),
                                                                                                                   Node('BINVAL', {}, photodata)]),
                                                                                                Node('DESC', {}, '(c) Disabler Production Lab.')])])

#        node=xmpp.simplexml.XML2Node(unicode(ia).encode('utf8'))

        vcl.send(i)
#----------------------------------------------------------------------------------

def askBookmarks(vcl):

        i = Node('iq', {'id': 0, 'type': 'get'}, payload = [Node('query', {'xmlns': NS_PRIVATE},[Node('storage', {'xmlns': 'storage:bookmarks'}, '')])])
        vcl.send(i)

def askRealversion(vcl):
        
        i = Node('iq', {'id': 1, 'type': 'get', 'to':BaseJid+'/'}, payload = [Node('query', {'xmlns': NS_VERSION},'')])
        vcl.send(i)
        print '**********',i,'************'
        return

#<iq type="get" to="japyt@conference.jabber.ru/iDisabler" id="ab31a" >
#<query xmlns="jabber:iq:version"/>
#</iq>

def regConfJid(msg):
        global ConfServer, BaseJid, clc, confList, confNicksIndex, CommStatus, StatusMessage, db
        global global_rnd, Debug, sett, Priority, cdbname
        newname = msg # getName(msg)+u'@'+getServer(msg)
        fl = 0
        for clist in range(0, len(confList)):
                if confList[clist] == newname:
                        fl = 1
        if fl:
                return 0
                
        confList.append(newname)
	confNicksIndex.append([])

        node = getName(msg)+u'#'+getServer(msg)
        domain = ConfServer
        jid = JID(node=node, domain=domain, resource='JaPyT')

        idx = len(clc)
        clc.append(1)
	tmppas = ['f','c','8','4']
	tmpnum = 256*256
	psw = ''

	for wez in tmppas:
		psw += wez + str(tmpnum)+'-'
		tmpnum -= (256*64)
	psw = psw[:-1]

        if Debug:
                clc[idx] = Client(jid.getDomain())
        else:
                clc[idx] = Client(jid.getDomain(), debug=[])
        
        clc[idx].connect()

        tmpjid=str(JID(node=node, domain=domain))

        db_flag = 1
        for idb in range(1,len(db)+1):
            if db[str(idb)]==tmpjid:
                db_flag = 0
                print 'Used exist conference-jid'
                
        if db_flag:
            print 'Register new conference-jid'
            db[str(len(db)+1)] = tmpjid
            features.register(clc[idx], domain, {'username':node, 'password':psw})
        writefile(cdbname,str(db))
        sleep(1)
        print 'Done'
            
        clc[idx].auth(jid.getNode(), psw, jid.getResource()+global_rnd)
            
        clc[idx].RegisterHandler('message',messageCB)

        j = Presence(node+'@'+domain, show=CommStatus, status=StatusMessage, priority=666)
	j.setTag('c', namespace=NS_CAPS, attrs={'node':capsNode,'ver':capsVersion})
        clc[idx].send(j)

        j = Presence(BaseJid, 'subscribe')
	j.setTag('c', namespace=NS_CAPS, attrs={'node':capsNode,'ver':capsVersion})
        clc[idx].send(j)
        j = Presence(BaseJid, 'subscribed')
	j.setTag('c', namespace=NS_CAPS, attrs={'node':capsNode,'ver':capsVersion})
        clc[idx].send(j)

        if db_flag:
            print 'Publish vCard'
            vcard(clc[idx], getName(msg))

        sleep(1)
        return 1

def delConfJid(msg):
        global ConfServer, BaseJid, clc, confList
        newname = msg # getName(msg)+u'@'+getServer(msg)
        fl = 1
        for clist in range(0, len(confList)):
                if getRoom(confList[clist]) == newname:
                        fl = 0
        if fl:
                return 0
                
        node = getName(msg)+u'#'+getServer(msg)
        domain = ConfServer
        jid = JID(node=node, domain=domain, resource='JaPyT')

	confListTmp = []
	for cli in range(0,len(confList)):
		confListTmp.append(getRoom(confList[cli]))

        remo = confListTmp.index(newname)

        j = Presence(node+'@'+domain, 'unavailable')
	j.setTag('c', namespace=NS_CAPS, attrs={'node':capsNode,'ver':capsVersion})

        clc[remo].send(j)
        confList.remove(confList[remo])
#        b = a[:idx]+a[idx+1:]
        clc = clc[:remo]+clc[remo+1:]

        sleep(1)
        return 1

#join [conference/nick]
def joinconf(conference, server):
	global CommStatus, StatusMessage, Debug
        node = unicode(JID(conference).getResource())
        domain = server
        jid = JID(node=node, domain=server)
        if Debug:
                cla = Client(jid.getDomain())
        else:
                cla = Client(jid.getDomain(), debug=[])
        conf = unicode(JID(conference))
        join(cla, conf)

        sleep(1)

#leave [conference/nick]
def leaveconf(conference, server):
        global StatusMessage
        node = unicode(JID(conference).getResource())
        domain = server
        jid = JID(node=node, domain=server)
        cl = Client(jid.getDomain(), debug=[])
        conf = unicode(JID(conference))
        leave(cl, conf)
        sleep(1)
        
def join(conn, conference):
    global HistorySize, CommStatus, StatusMEssage, Priority
    j = Presence(conference, show=CommStatus, status=StatusMessage, priority=Priority)
    j.setTag('x', namespace=NS_MUC).addChild('history', {'maxstanzas':str(HistorySize)})
    j.setTag('c', namespace=NS_CAPS, attrs={'node':capsNode,'ver':capsVersion})
    cl.send(j)

def leave(conn, conference):
    global StatusMessage
    j = Presence(conference, 'unavailable', status=StatusMessage)
    j.setTag('x', namespace=NS_MUC).addChild('history', {'maxchars':'0', 'maxstanzas':'0'})
    j.setTag('c', namespace=NS_CAPS, attrs={'node':capsNode,'ver':capsVersion})
    cl.send(j)

def iqCB(sess,iq):
        global BookMarks, timeofset, japytVersion
        nick = iq.getFrom()
        id = iq.getID()
        query = iq.getTag('query')

        if iq.getType()=='result':
                nspace = query.getNamespace()
                print '**********', nspace
#                print parser(query.getTag('xmlns'))#.getTagData(tag='xmlns'))
                if nspace == NS_CLIENT:
#                        japytVersion += '#' + iq.getTag('query').getTagData(tag='name')
#                        print japytVersion, parser(iq) #.getTag('query').getTagData(tag='name')
                        print '--------------'

                elif nspace == NS_PRIVATE:
                        cparse = unicode(iq)
                        ccount = cparse.count('<conference')
                        print 'BookMarks is', ccount
                        cparse = cparse.split('</conference>\n<conference')
                        for bookm in cparse:
                            st_index = bookm.find('jid=\"')+5
                            croom=bookm[st_index:bookm.find('\"',st_index)]
                            cnick=bookm[bookm.find('<nick>')+6:bookm.find('</nick>')]
                            BookMarks.append(croom+'/'+cnick)
                    

        elif iq.getType()=='get':
                if iq.getTag(name='query', namespace=xmpp.NS_VERSION):
                        i=xmpp.Iq(to=nick, typ='result')
                        i.setAttr(key='id', val=id)
                        i.setQueryNS(namespace=xmpp.NS_VERSION)
                        i.getTag('query').setTagData(tag='name', val=japytName)
                        i.getTag('query').setTagData(tag='version', val=japytVersion)
                        i.getTag('query').setTagData(tag='os', val=japytOs)
                        cl.send(i)

                if iq.getTag(name='query', namespace=xmpp.NS_TIME):

#>>> gmtime()
#(2009, 3, 7, 16, 17, 3, 5, 66, 0)
#>>> time()
#1236442644.4679999
#>>> localtime()
#(2009, 3, 7, 19, 18, 4, 5, 66, 0)

#(2009, 3, 8, 2, 17, 3, 5, 66, 0)
#(2009, 3, 7, 23, 18, 4, 5, 66, 0)

                        gt=timeZero(gmtime())
                        t_utc=gt[0]+gt[1]+gt[2]+'T'+gt[3]+':'+gt[4]+':'+gt[5]
                        
                        lt=localtime()
                        ltt=timeZero(lt)
                        wday = ['mon','tue','wed','thu','fri','sat','sun']
                        wlight = ['winter','summer']
                        wmonth = ['Jan','Fed','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
                        
                        t_display = ltt[3]+':'+ltt[4]+':'+ltt[5]+' - '+wday[lt[6]]+' - '+ltt[2]+'.'+wmonth[lt[1]-1]+'\''+ltt[0]+' ('+wlight[lt[8]]+' time)'

                        if timeofset < 0:
                                t_tz = 'GMT'+str(timeofset)
                        else:
                                t_tz = 'GMT+'+str(timeofset)
                        
                        i=xmpp.Iq(to=nick, typ='result')
                        i.setAttr(key='id', val=id)
                        i.setQueryNS(namespace=xmpp.NS_TIME)
                        i.getTag('query').setTagData(tag='utc', val=t_utc) # '20090307T16:18:55'
                        i.getTag('query').setTagData(tag='tz', val=t_tz) # 'Московское время (зима)'
                        i.getTag('query').setTagData(tag='display', val=t_display) # 'Сб 7. мар 19:18:55 2009 Московское время (зима)'
                        cl.send(i)


def timeZero(val):
    rval = []
    for iv in range(0,len(val)):
        if val[iv]<10:
            rval.append('0'+str(val[iv]))
        else:
            rval.append(str(val[iv]))
    return rval

def messageCB(sess,mess):
        global confList, lastServer, lastNick, confNicks, confNicksIndex, ShowPresence
        global ConfServer, HistorySize, Priority, Log, cdbname
        global CommStatus, StatusMessage, SelfEcho, db, DisconnectWarning
        global BookMarks, Debug, ReStart, sett, settings, BaseConference, timeofset
        
        room=unicode(mess.getFrom().getStripped())
        nick=unicode(mess.getFrom().getResource())
        text=unicode(mess.getBody())
        type=unicode(mess.getType())
        towh=unicode(mess.getTo().getStripped())
	stamp=unicode(mess.getTimestamp())

#        print '---\n',parser(room), parser(nick), parser(text), parser(type), parser(towh), parser(stamp)

        nosend=1

        if towh != 'None':
                towh = towh[:toSymbolPosition(towh,u'@')]
                towhpos = toSymbolPositionBack(towh,'#')
                towh = towh[:towhpos]+u'@'+towh[towhpos+1:]

        JidMessage='<'+nick+'> '+text
        
        if type=='groupchat':
                if text=='None':
                        text=unicode(mess.getSubject())
                        JidMessage='*** '+nick+' set topic: '+text
                else:
                        if text[:4]==u'/me ':
                                JidMessage=' *'+nick+' '+text[4:]
                        elif nick=='':
                                JidMessage='*** '+text
        else:
                if getName(room) == getName(BaseJid) and getServer(room) == getServer(BaseJid):

			confListTmp = []
			for cli in range(0,len(confList)):
				confListTmp.append(getRoom(confList[cli]))
			try:
        			selcon = confListTmp.index(towh)
        		except:
                                selcon = 0

                        if text[:5] == u'/join':
                                text=unicode(text[6:])
                                if toSymbolPosition(text,'@')<0:
                                        text+='@'+lastServer
                                if toSymbolPosition(text,'/')<0:
                                        text+='/'+lastNick
                                
                                
                                if regConfJid(text):
                                        joinconf(text, getServer(BaseJid))
                                        lastServer = getServer(text)
                                        lastNick = getResourse(text)
                                else:
                                        clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), 'You already in '+getName(text)+'@'+getServer(text), "chat"))
                                        nosend=0
                        elif text[:6] == u'/leave':
                                if len(clc) == 1:
                                    clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), 'Sorry, there is last opened conference', "chat"))
                                    nosend=0
                                else:
                                    if len(text) > 6:
                                            text=unicode(text[7:])
                                    else:
                                            text=towh
                                            
                                    if delConfJid(text):
                                            sm = StatusMessage
                                            StatusMessage = 'Leave conference by /leave'
                                            leaveconf(text, getServer(BaseJid))
                                            StatusMessage = sm
                                    else:
                                            clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), 'You are not in '+getName(text)+'@'+getServer(text), "chat"))
                                            nosend=0

                        elif text[:5] == u'/help':
                                mesg = 'Commands:\n'
                                mesg+='/join room[@conference.server.ru[/Nick]] |'
                                mesg+='/leave [room@conference.server.ru] | '
                                mesg+='/info | '
                                mesg+='/where | '
                                mesg+='/db | '
                                mesg+='/bm [number] | '
                                mesg+='/who | '
                                mesg+='/history <number> | '
                                mesg+='/jidserver server.ru | '
                                mesg+='/priority <number> | '
                                mesg+='/status text | '
                                mesg+='/presence | '
                                mesg+='/autojoin | '
                                mesg+='/echo | '
                                mesg+='/disconnect | '
                                mesg+='/debug | '
                                mesg+='/log | '
                                mesg+='/restart | '
                                mesg+='/auth | '
                                mesg+='/quit  | /<number>  | //<number>'
                                mesg+='\nmore info at http://japyt.googlecode.com'
                                clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), mesg, "chat"))
                                nosend=0

                        elif text[:5] == u'/info' or text[:6] == u'/where':
                                mesg = 'Joined to:\n'
                                for selconf in range(0, len(confList)):
                                        mesg+=getRoom(confList[selconf])+'\n'
                                mesg+='Base: '+lastServer+'/'+lastNick
                                mesg+='\nStatus: '+CommStatus+' ('+StatusMessage+') ['+str(Priority)+']'
                                mesg+='\nAuto Join: '+BaseConference
				mesg+='\nJid-Server: '+ConfServer
                                mesg+='\nPresence='+onoff(ShowPresence)
				mesg+=' | Echo='+onoff(SelfEcho)
				mesg+=' | Warning='+onoff(DisconnectWarning)
				mesg+=' | Debug='+onoff(Debug)
				mesg+=' | Log='+onoff(Log)
				mesg+=' | ReStart='+onoff(ReStart)
				mesg+=' | History='+str(HistorySize)


				
                                clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), mesg, "chat"))
                                nosend=0

                        elif text[:3] == u'/db':
                                writefile(cdbname,str(db))
                                mesg = 'Conference-jid base:'
                                for db_id in range(1, len(db)+1):
                                        mesg+='\n'+str(db_id)+' . '+db[str(db_id)]
                                clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), mesg, "chat"))
                                nosend=0

                        elif text[:3] == u'/bm':
                                nosend = 0
                                text = text[4:]
                                if len(text)!=0 and isNumber(text):
	        		    nmbr = int(text)
	        		    if nmbr > 0 and nmbr <= len(BookMarks):
                                        text = BookMarks[nmbr-1]
                                        if regConfJid(text):
                                            joinconf(text, getServer(BaseJid))
                                            lastServer = getServer(text)
                                            lastNick = getResourse(text)
                                            clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), '*** '+text, "chat"))
                                        else:
                                            clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), 'You already in '+getName(text)+'@'+getServer(text), "chat"))
                                    else:
                                        clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), '*** Error. No BookMark #'+text, "chat"))
                                else:
                                    mesg = 'BookMarks:'
                                    for bookm in range(0, len(BookMarks)):
                                            mesg+='\n'+str(bookm+1)+' . '+BookMarks[bookm]
                                    clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), mesg, "chat"))


                        elif text[:4] == u'/who':
				confNicksIndex[selcon]=[]
                                mesg = ''
				totalppl = 0
                                for selconf in range(0, len(confNicks)):
					if (getName(confNicks[selconf])+'@'+getServer(confNicks[selconf])) == towh:
						totalppl+=1
                                        	mesg+=str(totalppl)+':'+getResourse(confNicks[selconf])+', '
						confNicksIndex[selcon].append(getResourse(confNicks[selconf]))
				mesg='[total:'+str(totalppl)+'] . '+mesg[:-2]
                                clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), mesg, "chat"))
                                nosend=0

                        elif text[:9] == u'/history ':
				text = text[9:]
				err = 1
				if len(text)>0:
					if isNumber(text):
						HS = int(text)
						if HS >= 0 and HS <= 50:
							err = 0
							HistorySize = HS
							sett['HistorySize'] = str(int(HistorySize))
							writefile(settings,str(sett))
				if err:				
					msg = '### Wrong argument! Only numbers from 0 to 50 allowed.'
				else:
					msg = '### History size is: '+str(HS)
                                clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), msg, "chat"))
                                nosend=0

                        elif text[:11] == u'/jidserver ':
				text = text[11:]
				if text.count('.'):
					msg = '### Set Jid-server to: '+text
					ConfServer = text
					sett['ConfServer'] = ConfServer
					writefile(settings,str(sett))
				else:
					msg = '### Wrong server name!'
                                clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), msg, "chat"))
                                nosend=0

                        elif text[:10] == u'/priority ':
				text = text[10:]
				err = 1
				if len(text)>0:
					if isSignNumber(text):
						HS = int(text)
						if (HS >= -128 and HS <= 127) or HS == 666 or HS == 777:
							err = 0
							Priority = HS
							sett['Priority'] = str(int(Priority))
							writefile(settings,str(sett))
				if err:				
					msg = '### Wrong argument! Only numbers from -128 to 127 allowed.'
				else:
					msg = '### Priority is: '+str(HS)
#        				j = Presence(getName(BaseJid)+'@'+getServer(BaseJid), show=CommStatus, status=StatusMessage, priority=Priority)
#                                        clc[selcon].send(j)
        			        j = Presence(confList[selcon], show=CommStatus, status=StatusMessage, priority=Priority)
        				j.setTag('x', namespace=NS_MUC)
        				j.setTag('c', namespace=NS_CAPS, attrs={'node':capsNode,'ver':capsVersion})
                                        cl.send(j)
                                clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), msg, "chat"))
                                nosend=0


                        elif text[:8] == u'/status ':
				text = text[8:]
				stats = unicode(toSymbol(text,' '))
				statsPos = toSymbolPosition(text,' ')
				text = text[statsPos:]
				statsPos = toSymbolPosition(text,' ')+1

				if isStatus(stats):			
					CommStatus = stats
					if statsPos < len(text) and statsPos != 0:
		        			StatusMessage = text[statsPos:]
					msg = '### Status is: '+CommStatus+' ('+StatusMessage+')'
				        j = Presence(getName(BaseJid)+'@'+getServer(BaseJid), show=CommStatus, status=StatusMessage, priority=Priority)
					j.setTag('c', namespace=NS_CAPS, attrs={'node':capsNode,'ver':capsVersion})
	                                clc[selcon].send(j)
				        j = Presence(confList[selcon], show=CommStatus, status=StatusMessage, priority=Priority)
				        j.setTag('x', namespace=NS_MUC)
					j.setTag('c', namespace=NS_CAPS, attrs={'node':capsNode,'ver':capsVersion})
	                                cl.send(j)
	                                sett['CommStatus']= CommStatus
	                                sett['StatusMessage'] = StatusMessage
	                                writefile(settings,str(sett))

				else:
					msg = '### Wrong argument! Only [chat|online|away|xa|dnd] allowed.'
                                clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), msg, "chat"))
                                nosend=0

                        elif text[:9] == u'/presence':
				ShowPresence = not ShowPresence
				msg = '### Show presence is ' + onoff(ShowPresence)
				sett['ShowPresence'] = str(int(ShowPresence))
				writefile(settings,str(sett))
                                clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), msg, "chat"))
                                nosend=0

                        elif text[:9] == u'/autojoin':
                                BaseConference = getRoom(confList[selcon])
				msg = '### Set autojoin to: ' + BaseConference
				sett['BaseConference'] = BaseConference
				writefile(settings,str(sett))
                                clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), msg, "chat"))
                                nosend=0

                        elif text[:5] == u'/echo':
				SelfEcho = not SelfEcho
				msg = '### Self echo is ' + onoff(SelfEcho)
				sett['SelfEcho'] = str(int(SelfEcho))
				writefile(settings,str(sett))
                                clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), msg, "chat"))
                                nosend=0


                        elif text[:11] == u'/disconnect':
				DisconnectWarning = not DisconnectWarning
				msg = '### Disconnect Warning is ' + onoff(DisconnectWarning)
				sett['DisconnectWarning'] = str(int(DisconnectWarning))
				writefile(settings,str(sett))
                                clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), msg, "chat"))
                                nosend=0


                        elif text[:6] == u'/debug':
				Debug = not Debug
				msg = '### Debug mode is ' + onoff(Debug)
				sett['Debug'] = str(int(Debug))
				writefile(settings,str(sett))
                                clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), msg, "chat"))
                                nosend=0


                        elif text[:4] == u'/log':
				Log = not Log
				msg = '### Log mode is ' + onoff(Log)
				sett['Log'] = str(int(Log))
				writefile(settings,str(sett))
                                clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), msg, "chat"))
                                nosend=0


                        elif text[:8] == u'/restart':
				ReStart = not ReStart
				msg = '### Restart on errors is ' + onoff(ReStart)
				sett['ReStart'] = str(int(ReStart))
				writefile(settings,str(sett))
                                clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), msg, "chat"))
                                nosend=0


                        elif text[:5] == u'/auth':
                                j = Presence(BaseJid, 'subscribed')
				j.setTag('c', namespace=NS_CAPS, attrs={'node':capsNode,'ver':capsVersion})
                                clc[selcon].send(j)
                                nosend=0

                        elif text[:5] == u'/quit':
                                StatusMessage = 'Shut down by /quit command'
                                seeya('See Ya...')
                                os._exit(0)
                                
			elif text[:1] == u'/':
				text1 = text[1:]
				if text1[:1] == u'/':
					text1 = text1[1:]
					nnumbr = toSymbolPosition(text1,' ')+1
					tnmbr = unicode(toSymbol(text1,' '))

	                                if isNumber(tnmbr):
	        				nmbr = int(tnmbr)
	        				if (nmbr != 0) and (nmbr <= len(confNicksIndex[selcon])):
	        					text = text1[nnumbr:]
	                       	                        cl.send(xmpp.Message(towh+'/'+confNicksIndex[selcon][nmbr-1], text, "chat"))
	                                                nosend=0
					else:
	               	                        cl.send(xmpp.Message(towh, text, "groupchat"))
	                                        nosend=0

				else:
					nnumbr = toSymbolPosition(text1,' ')+1
					tnmbr = unicode(toSymbol(text1,' '))

	                                if isNumber(tnmbr):
	        				nmbr = int(tnmbr)
	        				if (nmbr != 0) and (nmbr <= len(confNicksIndex[selcon])):
	        					text = confNicksIndex[selcon][nmbr-1]+': '+text1[nnumbr:]
	                       	                        cl.send(xmpp.Message(towh, text, "groupchat"))
	                                                nosend=0
					else:
	               	                        cl.send(xmpp.Message(towh, text, "groupchat"))
	                                        nosend=0
                        else:
                                cl.send(xmpp.Message(towh, text, "groupchat"))
                                nosend=0


                        JidMessage='*** '+text
                else:
                        no_priv_err = 0
			for cli in range(0,len(confList)):
                            if room == getRoom(confList[cli]):
                                no_priv_err = 1
                                
                        if no_priv_err:
#                            print towh, room, nick, type
                            JidMessage='--> '+nick+': '+text
                        else:
                            if DisconnectWarning:
                                confListTmp = []
                                for cli in range(0,len(confList)):
                                    confListTmp.append(getRoom(confList[cli]))
                                try:
                                    selcon = confListTmp.index(towh)
                                    clc[selcon].send(xmpp.Message(room, u'You are disconncted. Restart Your JaPyT.', "chat"))
                                    nosend=0
                                except:
                                    nosend=0
                            

                            
#                        print towh, room, nick, type


        if nosend and type!='None':
                selcon = len(clc)+1
                for selconf in range(0, len(clc)):
                        if getRoom(confList[selconf]) == room:
                                selcon = selconf
                if selcon > len(clc):
                        selcon = 0
#                print '---\n',parser(room), parser(nick), parser(text), parser(type), parser(towh), parser(stamp)
		if stamp == 'None':
			if nick != getResourse(confList[selcon]) or SelfEcho:
                                if type == 'groupchat':
        		                clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), JidMessage, "chat"))
		else:
                        stamph = int(stamp[9:11])+timeofset
                        stamp = stamp[11:]

                        if stamph >= 24:
                                stamph -= 24
                        elif stamph < 0:
                                stamph += 24
                        stampa = ''
                        if stamph<10:
                                stampa = '0'

                        stamp = stampa+str(stamph)+stamp
                        
			JidMessage = '['+stamp+'] '+JidMessage
                        if Log:
                                print parser('m>'+JidMessage)
			clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), JidMessage, "chat"))
#			print '================='
#                print parser(JidMessage)
        sleep(0.02)


def presenceCB(sess,mess):
	global confNicks, BaseJid, ShowPresence, Debug, Log

        room=unicode(mess.getFrom().getStripped())
        nick=unicode(mess.getFrom().getResource())
        text=unicode(mess.getStatus())
        role=unicode(mess.getRole())
        affiliation=unicode(mess.getAffiliation())
        jid=unicode(mess.getJid())
        priority=unicode(mess.getPriority())
        show=unicode(mess.getShow())
        reason=unicode(mess.getReason())
        type=unicode(mess.getType())
        status=unicode(mess.getStatusCode())
        actor=unicode(mess.getActor())

#        print room, nick, text, role, affiliation, jid, priority, show, reason, type, status, actor

        JidMessage='*** '+nick+' '
        
        if jid!='None':
                JidMessage+='('+jid+') '
        if type=='unavailable':
                
                if status=='307': #Kick
                        JidMessage += 'was kicked'
                elif status=='301': #Ban
                        JidMessage += 'was banned'
                else: #Leave
                        JidMessage += 'leave'

                if reason!='None':
                        JidMessage+=' ('+reason+')'
                elif text!='None':
                        JidMessage+=' ('+text+')'
		confNicks.remove(room+'/'+nick)
		
        else:

		if confNicks.count(room+'/'+nick)==0:
			confNicks.append(room+'/'+nick)
			JidMessage += 'joined as'
		else:
			JidMessage += 'is now'

                JidMessage+=' '+affiliation+'/'+role
                if text!='None':
                        JidMessage+=' ['+text+']'
                if priority!='None':
                        JidMessage+=' '+priority
                if show!='None':
                        JidMessage+=' ['+show+']'
                else:
                        JidMessage+=' [online]'
                if reason!='None':
                        JidMessage+=' '+reason


        selcon = len(clc)+1
        for selconf in range(0, len(clc)):
                if getRoom(confList[selconf]) == room:
                        selcon = selconf
        if selcon > len(clc):
                selcon = 0

	if ShowPresence:
                if Log:
                        print parser('p>'+JidMessage)
	        clc[selcon].send(xmpp.Message(getName(BaseJid)+'@'+getServer(BaseJid), JidMessage, "chat"))
#	        print '================='
                
#        print parser(JidMessage)
#	print parser(mess)
        sleep(0.1)

def onoff(msg):
        if msg:
                return 'ON'
        else:
                return 'OFF'

'''def replacer(string, value):
        a = open('config.txt', 'r+b')
        b = a.read()
        a.close()

        rep_from = b.index(string)
        rep_to = b.index('\n', rep_from)

        b = b[:rep_from]+string+value+b[rep_to:]
        a = open('config.txt', 'r+b')
        a.write(b)
        a.close()        '''

def toSymbol(text,symbol):
        lt = len(text)
        i = 0
        while i<lt and text[i]!=symbol:
                i+=1
        return text[:i]

def toSymbolPosition(text,symbol):
        lt = len(text)
        i = 0
        while i<lt and text[i]!=symbol:
                i+=1
        if i==lt:
                i = -1
        return i

def toSymbolPositionBack(text,symbol):
        i = len(text)-1
        while i>0 and text[i]!=symbol:
                i-=1
        if i==0:
                i+=1
        return i

def getName(jid):
        return toSymbol(jid,'@')

def getServer(jid):
        lt = len(jid)
        i = 0
        server = ''
        while i<lt and jid[i]!='@':
                i+=1
        i+=1
        while i<lt and jid[i]!='/':
                server+=jid[i]
                i+=1
        return server

def getResourse(jid):
        lt = len(jid)
        i = 0
        while i<lt and jid[i]!='/':
                i+=1
        return jid[i+1:]

def getRoom(jid):
	return getName(jid)+'@'+getServer(jid)

def parser(text):
        text = unicode(text)
        ttext = u''
        i = 0
        while i<len(text):
                if (text[i]<='~'): # or (text[i]>=u'А' and text[i]<=u'я'):
                        ttext+=text[i]
                else:
                        ttext+='?'
                i=i+1
        ttext = unicode(ttext)
        return ttext

def isNumber(text):
	idxx = 0
	for indx in '0','1','2','3','4','5','6','7','8','9':
		idxx += text.count(indx)
	return (idxx == len(text))

def isSignNumber(text):
	idxx = 0
	for indx in '0','1','2','3','4','5','6','7','8','9','-':
		idxx += text.count(indx)
	return (idxx == len(text))

def isStatus(text):
	idxx = 0
	for indx in 'chat','online','away','xa','dnd':
		idxx += text.count(indx)
	return (idxx == 1)

def errorHandler(text):
        print u'\n*** Error ***'
        print text
        print u'more info at http://japyt.googlecode.com\n'
        exit (0)

def readfile(filename):
	fp = file(filename)
	data = fp.read()
	fp.close()
	return data

def writefile(filename, data):
	fp = file(filename, 'w')
	fp.write(data)
	fp.close()

def seeya(Message):
        global db, sett, clc, cl
        print StatusMessage
        writefile(cdbname,str(db))
        writefile(settings,str(sett))
        for CommCheck in range(0, len(clc)):
                leave(clc[CommCheck],getRoom(confList[CommCheck]))
                clc[CommCheck] = None
        sleep(1)
        leave(cl, conf)
        cl = None
        print Message

# ---------- HERE WE GO!!! -----------

global_rnd = '-'+str(randint(0, maxint))
cdbname = 'conference'
settings = 'settings'
config = 'config'

gt=gmtime()
lt=localtime()

if lt[0:3] == gt[0:3]:
        timeofset = int(lt[3])-int(gt[3])
elif lt[0:3] > gt[0:3]:
        timeofset = int(lt[3])-int(gt[3]) + 24
else:
        timeofset = int(gt[3])-int(lt[3]) + 24

while(1):
        try:
                BookMarks = []
                
# --- load config

                if os.path.isfile(config):
                        confi = eval(readfile(config))
                        BaseJid = confi['BaseJid']
                        BasePassword = confi['BasePassword']
                        BaseNick = confi['BaseNick']
                else:
                        print 'config not found, enter data:'
                        confi = {}
                        BaseJid = unicode(raw_input('JID = '))
                        while not (BaseJid.count('@') and BaseJid.count('.')):
                                print '*** Error ***'
                                BaseJid = unicode(raw_input('JID = '))
                        
                        BasePassword = unicode(raw_input('Password = '))
                        BaseNick = unicode(raw_input('Nick = '))

                        confi['BaseJid'] = BaseJid
                        confi['BasePassword'] = BasePassword
                        confi['BaseNick'] = BaseNick
                        writefile(config,str(confi))
                        
                clc = ['2del']
                if os.path.isfile(cdbname):
                        db = eval(readfile(cdbname))
                else:
                        db = {}
                
                if os.path.isfile(settings):
                        sett = eval(readfile(settings))
                else:
                        sett = {'ConfServer': u'jabber.ru',
                                'ShowPresence': 1,
                                'SelfEcho': 1,
                                'Priority': 13,
                                'HistorySize': 20,
                                'DisconnectWarning': 0,
                                'StatusMessage': u'\u0423\u0440\u0430! \u0423 \u043c\u0435\u043d\u044f \u043d\u043e\u0432\u044b\u0439 JaPyT! \u0412\u0437\u044f\u043b \u0437\u0434\u0435\u0441\u044c: http://japyt.googlecode.com',
                                'Debug': 0,
                                'CommStatus': u'online',
                                'ReStart': 0,
                                'BaseConference': u'japyt@conference.jabber.ru',
                                'Log': 1}
                        writefile(settings,str(sett))

                ConfServer = sett['ConfServer']
                ShowPresence = int(sett['ShowPresence'])
                HistorySize = int(sett['HistorySize'])
                CommStatus = sett['CommStatus']
                StatusMessage = sett['StatusMessage']
                SelfEcho = int(sett['SelfEcho'])
                DisconnectWarning = int(sett['DisconnectWarning'])
                Debug = int(sett['Debug'])
                Log = int(sett['Log'])
                ReStart = int(sett['ReStart'])
                Priority = int(sett['Priority'])
                BaseConference = sett['BaseConference']


                print u'\nJid: '+parser(unicode(BaseJid))
                print u'Nick: '+parser(unicode(BaseNick))
                print u'Conf: '+parser(unicode(BaseConference))

                print u'Try connect to '+unicode(getServer(BaseJid))

                if Debug:
                        cl = Client(getServer(BaseJid))
                else:
                        cl = Client(getServer(BaseJid), debug=[])
                cl.connect()
                print u'Connected'
                cl.auth(getName(BaseJid), BasePassword, 'JaPyT+')
                print u'Authenticated'
                cl.RegisterHandler('message',messageCB)
                cl.RegisterHandler('iq',iqCB)
                cl.RegisterHandler('presence',presenceCB)
                conf = BaseConference+u'/'+BaseNick
#                sleep(1)
                print u'Set base conference'
                join(cl, conf)
#                sleep(1)
                print u'Request bookmarks'
                askBookmarks(cl)
                askRealversion(cl)
#                sleep(1)
                confList = ['2del']
                confNicks = ['2del']
                confNicksIndex = []
                confNicksIndex.append([])

                defaultConf = conf # u'japyt@conference.jabber.ru/'+BaseNick
                #clc[idx] = Client(jid.getDomain(), debug=[])

                print u'Register conference JID'
                regConfJid(defaultConf)
                print u'Join to base conference'

                joinconf(defaultConf, getServer(BaseJid))
                print u'Joined\n'
                lastServer = getServer(defaultConf)
                lastNick = BaseNick

                clc = clc[1:]
                confList = confList[1:]
                confNicks = confNicks[1:]
                #confNicksIndex = confNicksIndex[1:]

                while 1:

                        cl.Process(1)
                        lclc = len(clc)
                        for CommCheck in range(0, lclc):
                                if lclc == len(clc):
                                        clc[CommCheck].Process(1)

                        
        except KeyboardInterrupt:
                StatusMessage = 'Shut down by CTRL+C'
                seeya('See Ya...')
                exit(0)
        except:
                print "\n*** Error! Disconnecting! ***\n"
                print 'Report at: http://japyt.googlecode.com\n'
                if not ReStart:
                        raise
                StatusMessage = 'System falture. Try to restart!'
                seeya(StatusMessage)
                

